﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;

namespace SharpSoft.WPF
{
    /// <summary>
    /// 程序集资源辅助方法
    /// </summary>
    public class ResourceHelper
    {
        /// <summary>
        /// 获取程序集资源文件夹中的资源数据流
        /// </summary>
        /// <param name="assembly"></param>
        /// <param name="folder"></param>
        /// <returns></returns>
        public static Dictionary<string, Stream> GetResourceInFolder(Assembly assembly, string folder)
        {
            var allresnames = assembly.GetManifestResourceNames();
            Dictionary<string, Stream> sorted = new Dictionary<string, Stream>();
            foreach (string name in allresnames)
            {
                Dictionary<string, Stream> dic = new Dictionary<string, Stream>();
                Stream st = assembly.GetManifestResourceStream(name);
                try
                {
                    ResourceReader resourceReader;
                    try
                    {
                        resourceReader = new ResourceReader(st);
                    }
                    catch (Exception)
                    {//不是有效的项目资源
                        continue;
                    }
                    using (resourceReader)
                    {
                        foreach (DictionaryEntry resourceEntry in resourceReader)
                        {
                            if (resourceEntry.Key is string relpath)
                            {
                                if (resourceEntry.Value is Stream stream)
                                {
                                    var f = System.IO.Path.GetDirectoryName(relpath).Replace("\\", "/");
                                    Uri u1 = new Uri(f, UriKind.Relative);
                                    if (folder.StartsWith("/"))
                                    {//去掉头部的斜杠
                                        folder = folder.TrimStart('/');
                                    }
                                    var u2 = new Uri(folder, UriKind.Relative);
                                    if (Uri.Compare(u1, u2, UriComponents.Path, UriFormat.UriEscaped, StringComparison.OrdinalIgnoreCase) == 0)
                                    {
                                        dic.Add(relpath, stream);
                                    }
                                }
                            }
                        }
                    }
                }
                catch (ArgumentException ex)
                {
                    throw new Exception("读取资源清单出错。", ex);
                }
                string[] keys = new string[dic.Count];
                var i = 0;
                foreach (var item in dic.Keys)
                {
                    keys[i] = item;
                    i++;
                }
                Array.Sort(keys);//使用资源名进行排序
                foreach (var key in keys)
                {
                    sorted.Add(key, dic[key]);
                }


            }
            return sorted;
        }
        /// <summary>
        /// 异步获取程序集资源文件夹中的资源数据流
        /// </summary>
        /// <param name="assembly"></param>
        /// <param name="folder"></param>
        /// <returns></returns>
        public static async Task<Dictionary<string, Stream>> GetResourceInFolderAsync(Assembly assembly, string folder)
        {
            return await Task.Run<Dictionary<string, Stream>>(
                () => GetResourceInFolder(assembly, folder)
                );

        }
        /// <summary>
        /// 获取资源文件夹内的所有图片（文件夹内不能有其他类型的文件）
        /// </summary>
        /// <param name="assembly"></param>
        /// <param name="folder"></param>
        /// <returns></returns>
        public static async Task<ImageSource[]> GetImagesInFolderAsync(Assembly assembly, string folder)
        {
            var dic = await GetResourceInFolderAsync(assembly, folder);
            List<ImageSource> list = new List<ImageSource>(dic.Count);
            foreach (var stream in dic.Values)
            {
              var bmp=await  BitmapHelper.LoadAsync(stream);
                list.Add(bmp);
            }
            return list.ToArray();
        }
    }
}
